package com.yy.tech.data.helper;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import com.yy.tech.data.context.SecretContent;
import com.yy.tech.data.mapper.filter.FilterConfiguration;
import com.yy.tech.data.mapper.filter.DesensitizePropertyFilter;
import com.yy.tech.data.mapper.introspector.DesensitizeAnnotationIntrospector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yy
 * @date 2022/4/8
 * @description: TODO
 */
@Component
public class DesensitizeHelper {

    @Autowired
    private DesensitizeAnnotationIntrospector introspector;
    @Autowired
    private DesensitizePropertyFilter propertyFilter;
    @Autowired
    private Environment env;

    @Autowired
    private List<ObjectMapperInitializer> initializers;

    public ObjectMapper help(){
        ObjectMapper mapper = new ObjectMapper();
        return help(mapper);
    }
    public ObjectMapper help(ObjectMapper mapper){
        mapper.setDateFormat(new SimpleDateFormat(env.getProperty(SecretContent.KEY_JACKSON_DATE_FORMAT, SecretContent.DATE_FORMAT)));
        if (!CollectionUtils.isEmpty(initializers)){
            initializers.forEach(i->{
                i.initialize(mapper);
            });
        }
        mapper.setAnnotationIntrospector(introspector);
        Map<Class<?>,Class<?>> mixins = new HashMap<>(8);
        mixins.put(Map.class, FilterConfiguration.MapPropertyFilterView.class);
        mixins.put(Object.class, FilterConfiguration.DesensitizeFilterView.class);
        mapper.setMixIns(mixins);
        mapper.setFilterProvider(new SimpleFilterProvider().addFilter(SecretContent.MAPPER_FILTER_NAME,propertyFilter).addFilter(SecretContent.MAPPER_MAP_FILTER_NAME,propertyFilter));
        return mapper;
    }
}
